package com.moli.lumpSugar.websocket.service.impl;

import cn.hutool.core.util.StrUtil;

import com.moli.lumpSugar.api.client.user.UserClient;
import com.moli.lumpSugar.api.domain.entity.user.User;
import com.moli.lumpSugar.websocket.service.WebSocketService;
import com.moli.lumpSugar.websocket.service.WxMsgService;
import com.moli.lumpSugar.websocket.service.adapter.TextBuilder;
import com.moli.lumpSugar.websocket.service.adapter.UserAdapter;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class WxMsgServiceImpl implements WxMsgService {
    @Autowired
    @Lazy
    private WebSocketService websocketService;
    @Autowired
    private UserClient userClient;
    @Value("${wx.mp.callback}")
    private String callback;
    /*
    * openId 和 登录code 对应关系
    * */
    private static final ConcurrentHashMap<String, Integer> WITE_AUTHORIZE_MAP = new ConcurrentHashMap<>();

    private final static String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    private final static String REPLACE_TEXT = "qrscene_";

    @Override
    public WxMpXmlOutMessage scan(WxMpXmlMessage wxMpXmlMessage, WxMpService wxMpService) {
        String openId = wxMpXmlMessage.getFromUser();
        Integer code = getEventKey(wxMpXmlMessage);
        websocketService.scanSuccess(code);
        if (Objects.isNull(code)) {
            return null;
        }
        // 根据openId，去本地查询是否存在用户
        User user = userClient.getUserByOpenId(openId);
//        User user = userDao.queryUserByOpenId(openId);
        boolean isRegister = Objects.nonNull(user);
        boolean isAuthor = isRegister && StringUtils.isNotBlank(user.getAvatar());
        if (isRegister && isAuthor) {
            // 登录成功，通过code找到对应的channel推送消息
            websocketService.scanLoginSuccess(code,user.getId());
            return new TextBuilder().build("登录成功", wxMpXmlMessage);
        }
        if (!isRegister) {
            // 通过用户构造器，构建用户user
            User insertUser = UserAdapter.buildUserSave(openId);
            userClient.updateUser(insertUser);
        }
        WITE_AUTHORIZE_MAP.put(openId, code);
        // 向微信申请用户授权的链接
        String authorizeUrl = String.format(URL, wxMpService.getWxMpConfigStorage().getAppId(), URLEncoder.encode(callback + "/wx/portal/public/callBack"));
        return new TextBuilder().build("点这里授权啦：<a href=\"" + authorizeUrl + "\">登录</a>", wxMpXmlMessage);
    }

    public void authorize(WxOAuth2UserInfo userInfo){
        String openid = userInfo.getOpenid();
        User oldUser = userClient.getUserByOpenId(openid);
        // 更新用户信息
        if (StrUtil.isBlank(oldUser.getAvatar())){
            fillUserInfo(oldUser.getId(),userInfo);
        }
        // 通过code找到用户对应的channel,进行登录
        Integer code = WITE_AUTHORIZE_MAP.remove(openid);
        websocketService.scanLoginSuccess(code,oldUser.getId());
    }

    private void fillUserInfo(Long uid, WxOAuth2UserInfo userInfo) {
        User user = UserAdapter.buildAuthorizeUser(uid,userInfo);
        userClient.updateUser(user);
//        userDao.updateById(user);
    }

    private Integer getEventKey(WxMpXmlMessage wxMpXmlMessage) {
        try {
            return Integer.parseInt(wxMpXmlMessage.getEventKey().replace(REPLACE_TEXT, ""));
        } catch (Exception e) {
            log.error("get EventKey error {}", wxMpXmlMessage.getEventKey(), e);
            return null;
        }
    }
}
